const adsDao = require("../dao/adsDao");

exports.getList = async (req, res) => {
  try {
    const ads = await adsDao.getAll();
    res.json({ code: 200, data: ads });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: "获取广告失败" });
  }
};

// adsController.js
exports.add = async (req, res) => {
  try {
    console.log("[add] body=", req.body); // 顺便打印参数
    const ad = req.body;
    const result = await adsDao.add(ad);
    res.json({ code: 200, message: "添加成功", data: result });
  } catch (err) {
    console.error("[add] catch error:", err); // ← 关键
    res.status(500).json({ code: 500, message: err.message || "添加广告失败" });
  }
};

exports.update = async (req, res) => {
  try {
    console.log("[update] id=", req.params.id, "body=", req.body);
    const { id } = req.params;
    const ad = req.body;
    await adsDao.update(id, ad);
    const updatedAd = await adsDao.getById(id);
    res.json({ code: 200, message: "更新成功", data: updatedAd });
  } catch (err) {
    console.error("[update] catch error:", err); // ← 关键
    res.status(500).json({ code: 500, message: err.message || "更新广告失败" });
  }
};

exports.remove = async (req, res) => {
  try {
    const { id } = req.params;
    await adsDao.remove(id);
    res.json({ code: 200, message: "删除成功" });
  } catch (err) {
    console.error(err);
    res.status(500).json({ code: 500, message: "删除广告失败" });
  }
};
